<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { delSpaceUsingPost, getSpaceVoByIdUsingGet } from '@/api/spaceController'
import { useLoginUserStore } from '@/stores/UseLoginUserStore'
import {listPictureVoByPageWithCacheUsingPost, searchPictureByColorUsingPost} from "@/api/pictureController"
import PictureList from "@/components/PictureList.vue"
import PictureSearchForm from "@/components/PictureSearchForm.vue";
import {ColorPicker} from "vue3-colorpicker";

const router = useRouter()
const route = useRoute()
const loginUserStore = useLoginUserStore()

const space = ref<API.SpaceVO>({})
const loading = ref(false)
const dataList = ref<API.PictureVO[]>([])
const total = ref<number>(0)

const searchParams = reactive<API.SpaceQueryRequest>({
  pageSize: 12,
  current: 1,
  spaceId: route.params.id as string,
  sortOrder: 'ascend',
  sortField: 'createTime'
})


const formatSize = (size?: number) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  return `${size.toFixed(2)} ${units[unitIndex]}`
}

const getSpaceById = async () => {
  try {
    loading.value = true
    const res = await getSpaceVoByIdUsingGet({
      id: route.params.id as string
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    }
  } finally {
    loading.value = false
  }
}

const getData = async () => {
  try {
    loading.value = true
    const res = await listPictureVoByPageWithCacheUsingPost(searchParams)
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records ?? []
      total.value = res.data.data.total ?? 0
    }
  } finally {
    loading.value = false
  }
}

const canEdit = computed(() => {
  return loginUserStore.loginUser?.id === space.value.userId || loginUserStore.loginUser?.userRole === 'admin'
})

const pagination = computed(() => ({
  current: searchParams.current,
  pageSize: searchParams.pageSize,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 张图片`,
  pageSizeOptions: ['12', '24', '48', '96'],
  onChange: (page: number, pageSize: number) => {
    searchParams.current = page
    searchParams.pageSize = pageSize
    getData()
  }
}))

const handleCreatePicture = () => {
  router.push(`/add_picture?spaceId=${route.params.id}`)
}
const onColorChange = async (color: string) => {
  const res = await searchPictureByColorUsingPost({
    picColor: color,
    spaceId: route.params.id,
  })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data ?? [];
    dataList.value = data;
    total.value = data.length;
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

onMounted(() => {
  getSpaceById()
  getData()
})
</script>

<template>
  <div class="space-container">
    <!-- 头部信息区 -->
    <a-flex class="header" justify="space-between" align="center">
      <a-flex gap="middle" align="center">
        <h1 class="title">{{ space.spaceName }}</h1>
        <a-tag color="blue">私有空间</a-tag>
      </a-flex>

      <a-flex gap="large" align="center">
        <a-button type="primary" @click="handleCreatePicture">
          <template #icon><PlusOutlined /></template>
          新建图片
        </a-button>

        <a-tooltip :title="`已使用 ${formatSize(space.totalSize)} / 总容量 ${formatSize(space.maxSize)}`">
          <a-progress
              type="dashboard"
              :percent="+(space.totalSize * 100 / space.maxSize).toFixed(1)"
              :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
          />
        </a-tooltip>
      </a-flex>
    </a-flex>
<!--    搜索表单-->
    <div class="search-wrapper">
      <PictureSearchForm class="glowing-border"></PictureSearchForm>
    </div>
    <!-- 按颜色搜索 -->
    <a-form-item label="按颜色搜索" style="margin-top: 16px">
      <color-picker format="hex" @pureColorChange="onColorChange" />
    </a-form-item>

    <!-- 图片列表 -->
    <div class="content-wrapper">
      <a-spin :spinning="loading">
        <PictureList
            :data-list="dataList"
            :pagination="pagination"
            :show-actions="canEdit"
            @refresh="getData"
        />

        <a-empty v-if="!loading && dataList.length === 0" description="暂无图片数据">
          <a-button type="primary" @click="handleCreatePicture">立即创建</a-button>
        </a-empty>
      </a-spin>
    </div>
  </div>
</template>

<style scoped lang="less">
.space-container {
  padding: 24px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9f5fb 100%);

  .header {
    padding: 16px 24px;
    margin-bottom: 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .title {
      margin: 0;
      font-size: 24px;
      color: #1d1d1d;
    }

    :deep(.ant-progress-inner) {
      width: 80px !important;
      height: 80px !important;
    }
  }

  .content-wrapper {
    padding: 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    :deep(.ant-empty) {
      padding: 48px 0;
    }
  }

  @media (max-width: 768px) {
    padding: 12px;

    .header {
      flex-direction: column;
      gap: 16px;
      align-items: flex-start;

      .title {
        font-size: 20px;
      }
    }

    .content-wrapper {
      padding: 12px;
    }
  }
}

@keyframes border-glow {
  0% { box-shadow: 0 0 10px rgba(99, 102, 241, 0.3); }
  50% { box-shadow: 0 0 20px rgba(99, 102, 241, 0.6); }
  100% { box-shadow: 0 0 10px rgba(99, 102, 241, 0.3); }
}

.space-container {
  padding: 24px;
  min-height: 100vh;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);

  .header {
    padding: 16px 24px;
    margin-bottom: 24px;
    background: rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(99, 102, 241, 0.2);
    transition: transform 0.3s ease;

    &:hover {
      transform: translateY(-2px);
    }

    .title {
      color: #e2e8f0;
      font-size: 24px;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    :deep(.ant-progress-inner) {
      width: 80px !important;
      height: 80px !important;

      .ant-progress-text {
        fill: #e2e8f0 !important;
      }
    }
  }

  .search-wrapper {
    margin: 24px 0;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: -10px;
      left: 50%;
      width: 80%;
      height: 20px;
      background: radial-gradient(circle, rgba(99, 102, 241, 0.3) 0%, transparent 70%);
      transform: translateX(-50%);
      filter: blur(15px);
    }
  }

  .content-wrapper {
    padding: 24px;
    background: rgba(30, 41, 59, 0.8);
    border-radius: 16px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(99, 102, 241, 0.2);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease;

    &:hover {
      transform: translateY(-2px);
    }

    :deep(.ant-empty) {
      .ant-empty-description {
        color: #94a3b8;
      }
    }
  }

  .glowing-border {
    animation: border-glow 3s ease-in-out infinite;
    border-radius: 16px;
    overflow: hidden;
  }

  @media (max-width: 768px) {
    padding: 12px;

    .header {
      flex-direction: column;
      gap: 16px;
      padding: 12px;

      .title {
        font-size: 20px;
      }

      :deep(.ant-progress) {
        transform: scale(0.8);
      }
    }

    .content-wrapper {
      padding: 12px;
      border-radius: 12px;
    }

    .search-wrapper {
      margin: 16px 0;
    }
  }
}
</style>
